import { createRouter, createWebHistory } from 'vue-router'
import { useTokenStore } from '@/stores/token.js'
import { ElMessage } from 'element-plus'

import LoginVue from '@/views/Login.vue'

import RegisterVue from '@/views/Register.vue'
import HomeVue from '@/views/Home.vue'

const routes = [
    { path: '/getShare/:id', component: () => import('@/views/GetShare.vue') },
    { path: '/', redirect: '/login' }, // 新增根路径重定向规则
    { path: '/login', component: LoginVue },
    { path: '/forget-password', component: () => import('@/views/ForgetPassword.vue') },
    { path: '/register', component: RegisterVue },
    { path: '/qqLogin', component: () => import('@/views/qqLogin.vue')},
    {
        path: '/home',
        component: HomeVue,
        children: [
            {
                path: '/',
                redirect: "/main/all"
            },
            {
                path: '/main/:category',
                name: '首页',
                meta: {
                    needLogin: true,
                    menuCode: "main"
                },
                component: () => import("@/views/main/Main.vue")
            },
            {
                path: '/myshare',
                name: '我的分享',
                meta: {
                    needLogin: true,
                    menuCode: "share"
                },
                component: () => import("@/views/share/Share.vue")
            },
            {
                path: '/recycle',
                name: '回收站',
                meta: {
                    needLogin: true,
                    menuCode: "recycle"
                },
                component: () => import("@/views/recycle/Recycle.vue")
            },
            {
                path: '/settings/userList',
                name: '用户管理',
                meta: {
                    needLogin: true,
                    menuCode: "settings"
                },
                component: () => import("@/views/admin/UserList.vue")
            },
            {
                path: '/settings/fileList',
                name: '用户文件',
                meta: {
                    needLogin: true,
                    menuCode: "settings"
                },
                component: () => import("@/views/admin/FileList.vue")
            }
        ]
    }
]


const router = createRouter({
    history: createWebHistory(),
    routes: routes
})

// 全局路由守卫
router.beforeEach((to, from, next) => {
    // 判断路由是否需要登录
    if (to.meta.needLogin) {
        const tokenStore = useTokenStore()
        // 检查是否有token
        if (Object.keys(tokenStore.token).length > 0) {
            next()
        } else {
            // 没有token，重定向到登录页
            ElMessage.error('请先登录')
            next('/login')
        }
    } else {
        next()
    }
})

// 导入已移至文件顶部

export default router